'use strict';

const Controller = require('egg').Controller;
const { Prefix, Post, Get, Delete } = require('egg-shell-decorators');
const FormData = require('form-data');
/**
 * @Controller 分类管理（目录管理）
 */
@Prefix('/api/v1/classify')
class ClassifyController extends Controller {
  /**
   * @summary 新增分类
   * @description
   * @router post /api/v1/classify/add
   * @request body addClassifyRules *body（DTO）
   * @response 200 baseResponse 创建成功（DTO）
   */
  @Post('/add')
  async addcClassify() {
    const { ctx, service, app } = this;
    // 参数校验
    const valiErrors = app.validator.validate(
      ctx.rule.addClassifyRules,
      ctx.request.body
    );
    // 参数校验未通过
    if (valiErrors) {
      ctx.helper.fail({ ctx, code: 422, res: valiErrors });
      return;
    }
    try {
      await service.classify.addClassify();
    } catch (error) {
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
  /**
   * @summary 查询分类树
   * @description ''
   * @router get /api/v1/classify/findTree
   * @response 200 classifyResponse
   */
  @Get('/findTree')
  async findClassify() {
    const { ctx, service, app } = this;
    try {
      await service.classify.findClassify();
    } catch (error) {
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
  /**
   * @summary 修改分类
   * @description ''
   * @router post /api/v1/classify/update
   * @request body updateClassifyRules
   * @response 200 baseResponse
   */
  @Post('/update')
  async updateClassify() {
    const { ctx, service, app } = this;
    // 参数校验
    const valiErrors = app.validator.validate(
      ctx.rule.updateClassifyRules,
      ctx.request.body
    );
    // 参数校验未通过
    if (valiErrors) {
      ctx.helper.fail({ ctx, code: 422, res: valiErrors });
      return;
    }
    try {
      await service.classify.updateClassify();
    } catch (error) {
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
  /**
   * @summary 删除分类
   * @description ''
   * @router delete /api/v1/classify/delete/{classify_id}
   * @request path string classify_id 分类id
   * @response 200 baseResponse
   */
  @Delete('/delete/:classify_id')
  async deleteClassify({ params: { classify_id } }) {
    const { ctx, service, app } = this;
    try {
      await service.classify.deleteClassify(classify_id);
    } catch (error) {
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
}

module.exports = ClassifyController;
